package com.itheima.controller;

import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.ProductService;
import com.itheima.service.UserService;
import com.itheima.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class MarketController {
    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserUtils userUtils;

    @GetMapping({"/" ,"/homePage"})
    public String showMainMarket(HttpSession session, Model model) {
        List<Product> latestProducts = productService.findLatestProducts(8);
        session.setAttribute("latestProducts", latestProducts);
        session.removeAttribute("error");
        session.setAttribute("userUtils", userUtils);
        return "homePage";
    }

    @RequestMapping("/homeSuccess")
    public String loginSuccess(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        session.removeAttribute("error");
        model.addAttribute("user", user);
        return "homePage";
    }

    @GetMapping("/home")
    public String home(HttpSession session) {
        // 直接重定向到主页
        return "redirect:/homePage";
    }

    @GetMapping("/userCenter")
    public String showUserCenter(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }

        //调用 Service 获取统计数据
        Map<String, Integer> stats = userService.getUserProductStats(user.getUserId());

        // 添加到 model
        model.addAttribute("productOnsaleQuantity", stats.get("onsale"));
        model.addAttribute("productSoldQuantity", stats.get("sold"));
        model.addAttribute("productPurchasedQuantity", stats.get("purchased"));
        model.addAttribute("productRemovedQuantity", stats.get("removed"));

        User newUser = userService.findUserById(user.getUserId());
        session.setAttribute("user", newUser);
        return "userCenter";
    }

}
